package com.y3k.servlet;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.y3k.mail.Mail;
import com.y3k.model.Notification;
import com.y3k.model.Variable;
import com.y3k.utils.ConnectionHelper;

public class EmailTask extends TimerTask {

	public static final Logger log = Logger.getLogger(EmailTask.class);

	private int runcounter;

	private Notification notification;

	public EmailTask(Notification notification) {
		this.notification = notification;
	}

	@Override
	public void run() {
		log.info("Notification [" + notification.getName() + " (" + runcounter + " times)]");

		Connection conn;
		try {
			conn = ConnectionHelper.getConnection();
			Statement stmt = conn.createStatement();

			log.info("Ejecutando [" + notification.getQuery() + "][" + notification.getVariables().size() + " variables]");
			ResultSet rs = stmt.executeQuery(notification.getQuery());
			while (rs.next()) {
				ResultSetMetaData metaData = rs.getMetaData();
				Column[] columns = new Column[metaData.getColumnCount()];
				for (int i = 0; i < metaData.getColumnCount(); i++) {
					Object element = rs.getObject(i + 1);
					columns[i] = new Column();
					columns[i].setName(metaData.getColumnName(i + 1));					
					if (element != null) {
						columns[i].setValue(element.toString());
						if (element.toString().contains(notification.getResult())) {
							sendMail(columns);
						}
					}
				}
			}
			stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		runcounter++;
	}

	private void sendMail(Column[] columns) {
		log.info("Notification [" + notification.getName() + "] contains [" + notification.getResult() + "]");
		String mailBody = notification.getMailBody();

		for (Iterator<Variable> it = notification.getVariables().iterator(); it.hasNext();) {
			Variable variable = it.next();
			mailBody = mailBody.replaceAll(variable.getName(), getValueForColumn(variable.getColumn(), columns));
		}

		String[] mailToList = notification.getMailTo().split(",");
		Mail.sendMessage(notification.getSubject(), mailBody, mailToList);
	}

	private String getValueForColumn(String columnName, Column[] columns) {
		for (int i = 0; i < columns.length; i++) {
			if (columns[i].getName().equals(columnName)) {
				return columns[i].getValue();
			}
		}
		return "[No data found]";
	}

	public Notification getNotification() {
		return notification;
	}
}